import account from '@service.account'
import storage from '@system.storage'



var userOpenIdKey = "user_openid"
var loginDataKey = "login_data"


function getPhoneNumber() {
  return new Promise((resolve, reject) => {
    account.authorize({
      appid: "103357791",
      type: "token",
      state: "feedbeef",
      scope: "scope.mobileNumber",        //此处必须设置为scope.mobileNumber
      success: function (data) {
        console.log("getPhoneNumber Authorize mobileNumber profile success data=" + JSON.stringify(data));
        account.getPhoneNumber({
          appid: "103357791",
          token: data.accessToken,
          encrypt: "true",
          success: function (data) {
            console.log("getPhoneNumber get mobile number success, number=" + data.phoneNumber);
            resolve(data.phoneNumber);
          },
          fail: function (data, code) {
            console.log("getPhoneNumber get mobile number fail, code=" + code);
            reject(data, code);
          }
        })
      },
      fail: function (data, code) {
        console.log("getPhoneNumber Authorize base profile fail, code=" + code);
        reject(data, code);
      }
    });
  });
}

function getCombineAccountInfo() {
  return new Promise((resolve, reject) => {
    account.authorize({
      appid: "103357791",
      type: "token",
      state: "feedbeef",
      scope: "scope.baseProfile",
      success: function (accountInfo) {
        console.log("Get account info from oauth success");
        getPhoneNumber()
          .then((phoneNumber) => {
            accountInfo.phoneNumber = phoneNumber
            resolve(accountInfo);
          })
          .catch((data, code) => {
            accountInfo.phoneNumber = "00000000000"
            resolve(accountInfo);
          });
      },
      fail: function (data, code) {
        reject(data, code);
      }
    })
  });
}

var login2Server = function () {
  var loginParam = {
    loginType: 1,
    niceName: "abc",
    phone: "153",
    pwd: "abc",
    unionid: "asdf",
  }
  this.$app.$def.$ajax.get('http://42.192.91.18:3020/user/login', loginParam)
    .then(result => {
      console.log(`Login result: ${result}`);
    })
    .catch(error => {
      global.$utils.showToast(`Something Error: ${error}`)
    })
    .finally(() => {
      global.$utils.showToast(`数据请求已完成`)
    })
  console.log("request finished");

}

function oAuthCallback(userData) {
  storage.set({
    key: userOpenIdKey,
    value: userData,
    success: function (data) {
      console.log("save oauth data success");
    },
    fail: function (data, code) {
      console.log("save oauth data failed, code = " + code);
    }
  });
}

function checkRegisterState() {
  return new Promise((resolve, reject) => {
    storage.get({
      key: loginDataKey,
      success: function (data) {
        if (data) {
          resolve(data);
        } else {
          reject(data);
        }
      },
      fail: function (data, code) {
        reject(data);
      }
    }
    )
  });
}

function register(callback) {
  console.log("Registering to server");
  return new Promise((resolve, reject) => {
    getCombineAccountInfo()
      .then((data) => {
        console.log("signInByBaseScope Authorize base profile success. data = ", data);
        // oAuthCallback(data.accountInfo);
        // var dataJson = JSON.parse(data.accountInfo);
        var regParam = {
          loginType: 1,
          niceName: data.nickname,
          phone: data.phoneNumber,
          pwd: "123456",
          unionid: data.unionid,
        }
        console.log("Reg param:", regParam);
        getApp().$ajax.post("http://42.192.91.18:3020/user/reg", regParam)
        .then((result)=>{
          console.log("Register success, ret = ",result);
        })
        .catch((data,code)=>{reject(data,code)});
      })
      .catch((data, code) => {
        console.log("signInByBaseScope Authorize base profile fail, code=" + code);
        reject("not implemented");
      });
  });
  // 1. get oauth
  // 2. try to register
  // 3. login to our server
}

function login(callback) {
  getCombineAccountInfo()
    .then((data, phone) => {
      console.log("signInByBaseScope Authorize base profile success.");
      oAuthCallback(data);

    })
    .catch((data, code) => { console.log("signInByBaseScope Authorize base profile fail, code=" + code) });

  var loginParam = {
    loginType: 1,
    niceName: "abc",
    phone: "153",
    pwd: "abc",
    unionid: "asdf",
  }
  getApp().$def.$ajax.get('http://42.192.91.18:3020/user/login', loginParam)
    .then(result => {
      console.log(`Login result: ${result}`);
    })
    .catch(error => {
      global.$utils.showToast(`Something Error: ${error}`)
    })
    .finally(() => {
      global.$utils.showToast(`数据请求已完成`)
    })
  console.log("request finished");
  // 1. get oauth
  // 2. try to register
  // 3. login to our server
}

export default {
  checkRegisterState,
  login,
  register,
  userOpenIdKey,
}